package filter;

import entity.SysDict;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import service.SysDictService;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xuweijie on 17-5-3.
 * 自定义表单过滤器
 */
public class CustomFromAuthenticationFilter extends FormAuthenticationFilter {

    @Autowired
    private SysDictService sysDictService;

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        ServletContext context = request.getServletContext();
        if (context.getAttribute("SysDict")==null){
            System.out.println("加载缓存...");
            List<SysDict> list = sysDictService.lists();
            Map<String,Map<String,String>> maps = new HashMap<String,Map<String,String>>();
            for (SysDict dict : list) {
                maps.computeIfAbsent(dict.getLabel(), k -> new HashMap<String,String>());
                maps.get(dict.getLabel()).put(dict.getType(),dict.getValue());
            }
            context.setAttribute("SysDict",maps);
        }
        return super.onAccessDenied(request, response);
    }

    /**
     * 登录成功后跳转到指定页面（后台首页）
     * 登录成功后将用户名存储到缓存里
     * */
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        ServletContext context = request.getServletContext();
        context.setAttribute("username",token.getPrincipal());
        WebUtils.getAndClearSavedRequest(request);//清除原先跳转的页面
        WebUtils.redirectToSavedRequest(request,response,getSuccessUrl());//设定跳转到指定页面
        return false;
    }

//    @Override
//    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
//        Subject subject=getSubject(request,response);
//        if(!subject.isAuthenticated() && subject.isRemembered()){
//            Session session=subject.getSession(true);
//            if(session.getAttribute("username")==null){
//                try {
//                    onAccessDenied(request,response);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
//        }
//        return subject.isAuthenticated() || subject.isRemembered();
//    }
}
